<template>
  <div class="app-container">
  <!--站点数据-->
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <el-form-item label="选择校区" prop="schoolId">
       <el-select v-model="queryParams.schoolId" placeholder="请选择" clearable filterable size="small" @keyup.enter.native="handleQuery" >
         <el-option
           v-for="dict in schoolOptions"
           :key="dict.value"
           :label="dict.name"
           :value="dict.id"
         />
       </el-select>
      </el-form-item>
      <el-form-item label="申请时间" prop="time">
        <el-date-picker
          v-model="queryParams.time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="状态" clearable size="small" >
          <el-option :key="999" :label="'全部'" :value="null" />
          <el-option
            v-for="dict in runnerStatusOptions"
            :key="dict.key"
            :label="dict.value"
            :value="dict.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="跑腿员类型" prop="flg">
        <el-select v-model="queryParams.flg" placeholder="类型" clearable size="small" >
          <el-option :key="999" :label="'全部'" :value="null" />
          <el-option
            v-for="dict in runnerTypeOptions"
            :key="dict.key"
            :label="dict.value"
            :value="dict.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="跑腿员姓名" prop="username">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="跑腿员手机号" prop="mobile">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          :type="tableTab === 1 ? 'primary':''"
          size="mini"
          @click="changType(1)"
        >待审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :type="tableTab === 2 ? 'primary':''"
          size="mini"
          @click="changType(2)"
        >已审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :type="tableTab === 3 ? 'primary':''"
          size="mini"
          @click="changType(3)"
        >历史发放</el-button>
      </el-col>
    </el-row>


    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="50" align="center" /> -->
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="卡券" align="center" width="360px">
        <template slot-scope="scope">
          <div class="coupon_card">
            <div class="coupon_card_content">
              <div class="coupon_card_content_left mr10" style="color: red;">
                ￥<span class="fs26">{{scope.row.amount}}</span>
              </div>
              <div class="coupon_card_content_right">
                <div class="fs16 text_ellipsis1" >{{scope.row.name}}</div>
                <div class="fs12 text_ellipsis1">满{{scope.row.limitAmount}}元使用</div>
              </div>
            </div>
            <div class="fs12 coupon_card_bottom">
              有效时间：{{scope.row.startTime.slice(0,-3) + ' - ' + scope.row.endTime.slice(0,-3) }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="ID" align="center" prop="id" width="110px" />
      <el-table-column label="适用校区" align="center">
        <template slot-scope="scope">
          <div style="cursor: pointer;" v-if="scope.row.allSchoolFlg == 1" @click="getOwnSchoolList(scope.row)">全部</div>
          <div style="cursor: pointer;" v-else @click="openOwnSchoolList(scope.row)">
            <div>指定校区</div>
            <div>（<span style="color: #46A6FF;font-weight: bold;">{{ scope.row.schoolCount }}</span>）</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="适用人群" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.allUserFlg == 1" >全部</span>
          <span v-else>{{ scope.row.userTypeList?scope.row.userTypeList.join(''):'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="insertOperator" />
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="tableTab==1" />
      <el-table-column label="发放数量" align="center" prop="totalCount" />
      <el-table-column label="已领取" align="center" v-if="tableTab==2||tableTab==3">
        <template slot-scope="scope">
          <span @click="openOwnUserList(scope.row)" style="color: #46A6FF;font-weight: bold;cursor: pointer;">{{ scope.row.sendCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已使用" align="center" prop="usedCount" v-if="tableTab==2||tableTab==3" />
      <el-table-column label="操作" align="center" width="240">
        <template slot-scope="scope" >
          <div v-if="tableTab==1">
            <el-button
              type="primary"
              size="mini"
              @click="handleCheck(scope.row, 1)"
            >通过</el-button>
            <el-button
              size="mini"
              @click="handleCheck(scope.row, 0)"
            >不通过</el-button>
          </div>
          <div v-if="tableTab==2 && scope.row.state!=-1">
            <el-button
              type="danger"
              size="mini"
              style="margin-bottom: 10px;"
              @click="handleStop(scope.row)"
            >停止发放</el-button>
            <el-button
              type="success"
              size="mini"
              style="margin-bottom: 10px;"
              @click="handleAddSchool(scope.row)"
            >新增适用校区</el-button>
          </div>
          <div v-if="tableTab==2 && scope.row.state==-1">
            <div>
              不通过原因：{{scope.row.checkMsg}}
            </div>
          </div>
          <div v-if="tableTab==3">
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(scope.row)"
            >编辑重启</el-button>
            <el-button
              type="success"
              size="mini"
              @click="handleAddSchool(scope.row)"
            >新增适用校区</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 适用校区详细 -->
    <el-dialog title="适用校区":inline="true" :visible.sync="schoolListOpen" width="800px">
      <el-form ref="form" :model="schoolQueryParams" label-width="120px" size="mini">
        <el-form-item :label="'指定校区'" prop="schoolId">
          <el-input
            v-model="schoolQueryParams.schoolName"
            placeholder="请输入校区名字"
            clearable
            size="small"
            style="width: 300px"
            @keyup.enter.native="handleQuerySchool"
          >
          </el-input>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuerySchool">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="ownSchoolList">
        <el-table-column label="校区ID" align="center" prop="schoolId" width="110px" />
        <el-table-column label="校区名称" align="center" prop="schoolName" />
        <el-table-column label="操作" align="center" width="240">
          <template slot-scope="scope" >
            <el-button
              type="primary"
              size="mini"
              @click="schoolHandleDelete(scope.row)"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="schoolListOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 领票人详细 -->
    <el-dialog title="领取详细":inline="true" :visible.sync="userListOpen" width="800px">
      <el-form ref="form" :model="userQueryParams" label-width="120px" size="mini">
        <el-form-item :label="'用户手机号'" prop="telephone">
          <el-input
            v-model="userQueryParams.telephone"
            placeholder="请输入用户手机号"
            clearable
            size="small"
            style="width: 300px"
            @keyup.enter.native="handleQueryUser"
          >
          </el-input>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQueryUser">搜索</el-button>
          <el-button type="success" icon="el-icon-edit" size="small" @click="exportOut">导出</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="ownUserList">
        <el-table-column label="卡券ID" align="center" prop="no" />
        <el-table-column label="用户手机号" align="center" prop="telephone" />
        <el-table-column label="用户名" align="center" prop="name" />
        <el-table-column label="校区" align="center" prop="schoolName" />
        <el-table-column label="发放时间" align="center" prop="createTime" />
        <el-table-column label="使用时间" align="center" prop="usedTime" />
        <el-table-column label="状态" align="center" prop="statusName" />
      </el-table>
      <pagination
        v-show="userTotal>0"
        :total="userTotal"
        :page.sync="userQueryParams.pageNum"
        :limit.sync="userQueryParams.pageSize"
        @pagination="getOwnUserList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="userListOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { exportUser, } from "@/api/system/user";
import { runnerOption,listRunnerCheck,listRunner,listRunnerDetails,listRunnerCheckDetails,editRunner,checkRunner } from "@/api/pt/runner.js";
import {
  listCouponCheck,listCoupon,listCouponOld,couponCheck,couponStop,
  listCouponSchool,listCouponSchoolDelete,listCouponSchoolAdd,
  listCouponUser,listCouponUserExcel
  } from "@/api/pt/coupon.js";
import { addSite } from "@/api/pt/site.js";
import { listSchool } from "@/api/pt/school.js";
import { getToken } from "@/utils/auth";

export default {
  name: "RunnerCheck",
  components: {},
  data() {
    return {
      // 列表数据简单e筛选
      tableTab: 1,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 表格数据
      tableList: null,
      // 已有校区数据
      schoolOptions: [],
      // 跑腿员状态
      runnerStatusOptions: [],
      // 跑腿员类型
      runnerTypeOptions: [],
      // 表单参数
      form: {
      },
      //校区详情打开
      schoolListOpen: false,
      ownSchoolList:[],
      // 查询校区参数
      schoolQueryParams: {
        couponId: undefined,
        pageNum: 1,
        pageSize: 999,
        schoolName: undefined,
      },

      //领取详情打开
      userListOpen: false,
      ownUserList:[],
      // 查询校区参数
      userQueryParams: {
        id: undefined,
        pageNum: 1,
        pageSize: 10,
        telephone: undefined,
      },
      userTotal: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined,
        schoolId: undefined,
        mobile: undefined
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "站点名称不能为空", trigger: "blur" }
        ],
        email: [
          { required: true, message: "邮箱地址不能为空", trigger: "blur" },
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getList();

    listSchool({pageNum: 1,pageSize: 10000}).then(response => {
      let list = response.data.list
      let lArr = ''
      let listArr = []
      list.map(item=>{
        if(lArr.indexOf(item.city) == -1) {
          lArr += ',' + item.city
        }
      })
      lArr = lArr.split(',')
      lArr.map(item=>{
        listArr.push({
          label: item ? item : '全部',
          value: item
        })
      })
      this.schoolOptions = response.data.list
    });
    runnerOption().then(response => {
      this.runnerStatusOptions = response.data.state
      this.runnerTypeOptions = response.data.type
    })
  },
  methods: {
    // 打开适用校区
    openOwnSchoolList(row){
      this.schoolListOpen = true
      if(row) {
        this.schoolQueryParams.couponId = row.id
      }
      this.getListCouponSchool()
    },
    /** 适用校区搜索按钮操作 */
    handleQuerySchool() {
      this.openOwnSchoolList();
    },
    // 获取适用校区列表
    getListCouponSchool(){
      let pa = {...this.schoolQueryParams}
      delete pa.couponId
      listCouponSchool(this.schoolQueryParams.couponId,pa).then(response => {
        this.ownSchoolList = response.data.list;
      });
    },
    // 删除校区
    schoolHandleDelete(row){
      listCouponSchoolDelete(this.schoolQueryParams.couponId,row.id).then(response => {
        this.msgSuccess("移除成功");
        this.getListCouponSchool();
        this.getList();
      });
    },
    /** 领取用户列表搜索按钮操作 */
    handleQueryUser() {
      this.openOwnUserList();
    },
    //  打开领取用户列表
    openOwnUserList(row){
      this.userListOpen = true
      this.userQueryParams.pageNum = 1
      if(row) {
        this.userQueryParams.id = row.id
      }
      this.getOwnUserList()
    },
    //  获取领取用户列表
    getOwnUserList(){
      this.loading = true;
      let pa = {...this.userQueryParams}
      delete pa.id
      listCouponUser(this.userQueryParams.id,pa).then(response => {
        this.ownSchoolList = response.data.list;
        this.usertotal = response.data.total;
        this.loading = false;
      });
    },
    // 导出领取用户列表
    exportOut(){
      let pa = {id: this.userQueryParams.id,telephone:this.userQueryParams.telephone}
      listCouponUserExcel(this.userQueryParams.id,pa).then(response => {
        let url = response.data;
        window.open(url)
      });
    },
    handleEdit(row){
      this.$router.push({
        path: '/pt_marketing/addCoupon',
        query: {
          id: row.id,
        }
      });
    },
    handleAddSchool(row){
      this.$prompt('补充适用校区ID', "", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(({ value }) => {
        return listCouponSchoolAdd(row.id,value);
      }).then(()=>{
        this.getList();
        this.msgSuccess("修改成功");
      }).catch(() => {});
    },
    handleStop(row){
      this.$confirm(`停止发放后不可恢复，请谨慎操作！`, "确定停止发放？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return couponStop(row.id);
      }).then(() => {
        this.getList();
        this.msgSuccess("修改成功");
      }).catch(function() {});
    },
    /** 审核 */
    handleCheck(row, state) {
      // let pa = JSON.parse(JSON.stringify(this.form))
      let pa = {
        "msg": '',
        "result": state
      }
      if(state === 1){
        this.$confirm(`是否通过审核？`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return couponCheck(row.id,pa);
        }).then(() => {
          this.getList();
          this.msgSuccess("修改成功");
        }).catch(function() {});
      }else {
        this.$prompt('请输入不通过理由', "不通过", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }).then(({ value }) => {
          pa.msg = value
          return couponCheck(row.id,pa);
        }).then(()=>{
          this.getList();
          this.msgSuccess("修改成功");
        }).catch(() => {});
      }

    },
    //切换table
    changType(e){
      this.tableTab = e
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      if(this.tableTab === 2){
        listCoupon(this.addDateRange2(this.queryParams, 'createTimeStart', 'createTimeEnd')).then(response => {
            this.tableList = response.data.list;
            this.total = response.data.total;
            this.loading = false;
          }
        );
      }else if(this.tableTab === 3){
        listCouponOld(this.addDateRange2(this.queryParams, 'createTimeStart', 'createTimeEnd')).then(response => {
            this.tableList = response.data.list;
            this.total = response.data.total;
            this.loading = false;
          }
        );
      }else {
        listCouponCheck(this.addDateRange2(this.queryParams, 'createTimeStart', 'createTimeEnd')).then(response => {
            this.tableList = response.data.list;
            this.total = response.data.total;
            this.loading = false;
          }
        );
      }
    },
    // 取消按钮
    cancel() {
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
      this.form = {
        id: undefined,
        schoolId: undefined,
        name: undefined,
        city: undefined,
        status: undefined,
        address: undefined,
        siteDescribe: undefined,
        personInCharge: undefined,
        mobile: undefined,
        personInCharge2: undefined,
        mobile2: undefined,
        time: undefined,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      console.log(row)
      // row.time = [new Date(row.startTime),new Date(row.endTime)]
      // this.form = row
      if(this.tableList === 2){
        listRunnerCheckDetails(row.id).then(response => {
          this.form = response.data
          this.form.time = [new Date(response.data.startTime),new Date(response.data.endTime)]
          this.form.sex = JSON.stringify(this.form.sex)
          this.form.schoolId = JSON.stringify(this.form.schoolId)
        })
      }else{
        listRunnerDetails(row.id).then(response => {
          this.form = response.data
          this.form.time = [new Date(response.data.startTime),new Date(response.data.endTime)]
          this.form.sex = JSON.stringify(this.form.sex)
          this.form.schoolId = JSON.stringify(this.form.schoolId)
        })
      }
      if(type === '详情') {
        this.detailOpen = true;
      }else {
      }
    },
  }
};
</script>

<style type="text/css">
  .dian {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    display: inline-block;
    background: #999;
    margin-right: 6px;
  }
  .coupon_card {
    width: 340px;
    min-height: 100px;
    border-radius: 10px;
    color: #FFFFFF;
    background: #409EFF;
    padding: 20px 20px 10px;
  }
  .coupon_card_content {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .coupon_card_content_left {
    flex: 0 0 60px;
  }
  .coupon_card_content_right {
    width: 210px;
  }
</style>
